package com.guarantee.server.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.guarantee.server.common.base.BaseServiceImpl;
import com.guarantee.server.domain.FoodElemeStorage;
import com.guarantee.server.domain.Order;
import com.guarantee.server.domain.Rule;
import com.guarantee.server.domain.Store;
import com.guarantee.server.mapper.FoodElemeStorageMapper;
import com.guarantee.server.mapper.OrderMapper;
import com.guarantee.server.service.IFoodElemeStorageService;
import com.guarantee.server.service.IOrderService;
import com.guarantee.server.service.IRuleService;
import com.guarantee.server.service.IStoreService;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author huisonglin
 * @Description
 * @PackageName autofood-rest
 * @Package com.guarantee.server.service.impl
 * @Date 2024-07-12 12:43
 * @Version 1.0
 */
@Log4j2
@Service
public class OrderServiceImpl extends BaseServiceImpl<OrderMapper, Order> implements IOrderService {

    static {
        System.setProperty("webdriver.chrome.driver","C:\\drive\\chromedriver.exe");
    }

    private WebDriver getWebDriver(){
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--disable-blink-features=AutomationControlled");
        chromeOptions.setExperimentalOption("useAutomationExtension",false);
        chromeOptions.setExperimentalOption("excludeSwitches",new String[]{"enable-automation"});
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
        return driver;
    }

    @Resource
    IFoodElemeStorageService foodElemeStorageService;

    @Resource
    IStoreService storeService;

    @Resource
    IRuleService ruleService;

    @Override
    @SneakyThrows
    public void out(Order order) {
        WebDriver webDriver = getWebDriver();
        try {
            webDriver.get("https://melody.shop.ele.me/login");
            JavascriptExecutor js = (JavascriptExecutor) webDriver;
            LambdaQueryWrapper<FoodElemeStorage> query = Wrappers.<FoodElemeStorage>lambdaQuery();
            query.eq(FoodElemeStorage::getStoreId, order.getStoreId());
            FoodElemeStorage foodElemeStorage = foodElemeStorageService.selectOne(query);
            String storage = foodElemeStorage.getStorage();
            Map map = JSON.parseObject(storage, Map.class);
            for (Object o : map.keySet()) {
                try {
                    String script = "window.localStorage.setItem('"+o+"','"+map.get(o)+"')";
                    js.executeScript(script);
                } catch (Exception e) {
                    log.error("",e);
                }
            }
            Store store = storeService.selectById(order.getStoreId());
            webDriver.get("https://melody.shop.ele.me/app/shop/"+store.getRegionId()+"/order__processing#app.shop.order.processing");
            webDriver.switchTo().frame("app_shop_order_processing");
            loadFinlish(webDriver);
            js.executeScript("document.querySelector(\"#rc-tabs-0-tab-all > span > span\").click()");
            Thread.sleep(1000L);
            try {  //进行判断
                if(StringUtils.isBlank(order.getIncome())){
                    String income = (String) js.executeScript("return document.querySelector(\"#\\\\38 "+order.getOutTradeNo().substring(1)+" > div.order-card-item__2m71tc1Es8xRDBwVQ0-tog > div.order-card-itemRight__gZnAP-2wmW-uidO2qhMs0 > div.expectedIncome__1_9MNgOynAKQJCiZmGQSEk > div:nth-child(2) > span\").innerText");
                    System.out.println("获取到的income为"+income);
                    income = income.replace("¥","");
                    order.setIncome(income);
                    this.updateById(order);
                    LambdaQueryWrapper<Rule> ruleQuery = Wrappers.<Rule>lambdaQuery();
                    ruleQuery.eq(Rule::getStoreId,store.getId());
                    Rule rule = ruleService.selectOne(ruleQuery);
                    Integer time = ruleService.getTime(rule.getId(), income);
                    log.info("获取到的理论出餐时间为"+time);
                    log.info("获取到的最低出餐时间为"+rule.getTime());
                    if(!time.equals(rule.getTime()) ){
                        log.info("time={},rule.gettime={}",time,rule.getTime());
                        order.setTheoryOutTime(new Date(order.getTheoryOutTime().getTime()+((time-rule.getTime())*1000*60)));
                        order.setOutStatus("READY");
                        this.updateById(order);
                        return;
                    }
                }
            } catch (Exception e) {
            }
            String a = "document.querySelector(\"#\\\\38 "+order.getOutTradeNo().substring(1)+" > div.meal-complete-content__629EC9g1eSK9XyD7yb-Ok.order-content-base__1KDsrTr1JhR-nZefiIqb84 > button\").click()";
            log.info(a);
            js.executeScript(a);
            Thread.sleep(1000L);
            try {
                //点击真实上报
                js.executeScript("document.querySelector(\"body > div > div > div > div > div.ant-popover-inner > div > div.ant-popover-buttons > button.ant-btn.ant-btn-primary.ant-btn-sm\").click()");
                log.error("成功点击了真实上报");
            } catch (Exception e) {
                log.error("点击真实上报错误");
            }
            Thread.sleep(1000L);
            order.setOutStatus("OUTED");
            order.setOutFoodTime(new Date());
            this.updateById(order);
        } catch (Exception e) {
            throw e;
        }finally {
            webDriver.quit();
        }

    }






    public void loadFinlish(WebDriver webDriver){
        new WebDriverWait(webDriver, 3).until((WebDriver driver) -> {
            JavascriptExecutor js = (JavascriptExecutor) driver;
            Boolean result = (Boolean) js.executeScript("return document.readyState === 'complete'");
            log.info("页面是否已经加载完成"+result);
            return result;
        });
    }
}
